import React from "react";
import {Link} from 'react-router';
import config from '../../config';
import {getItem,setItem} from '../../utils';

/**
 * 加载图片或样式文件
 * */
import './sass/Header.scss';
import avatar from '../../containers/_common_img/sponsor/head.png';


export default class Header extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };
    constructor(props) {
        super(props);
        this.handleSidebarVisible = this.handleSidebarVisible.bind(this);
        this.state = {
            sidebarVisible: false
        }
    }

    componentDidMount() {
        const {actions,location} = this.props;
        let openid = location.query.openid;
        let token = location.query.token;
        openid && setItem('openid',openid);
        token && setItem('token',token);
        if(token || getItem('token')){
            actions.fetchUserInfo();
        }
    }
    componentWillUnmount(){
        this.setState({
            sidebarVisible: false
        })
    }


    handleSidebarVisible(){
        const {actions} = this.props;
        if(getItem('token')){
            this.setState({sidebarVisible: !this.state.sidebarVisible})
        }else{
            setItem("NEXT_URL","/activityList");
            window.location.href = config.SERVICE_URL+'/api/wechat/authorize?url='+escape(config.JUMP_URL+'/#/login');
        }
    }
    render() {
        const { user,title } = this.props;
        return (
            <div className="header">
                <i className="icon-user" onClick={this.handleSidebarVisible}/>
                <span>{title}</span>

                <div className={this.state.sidebarVisible ? 'side-bar' : 'hide' } onClick={this.handleSidebarVisible}>
                    <div className="user-info" onClick={e => {e.stopPropagation()}}>
                        <div className="user-head">
                            <img src={user && user.userInfo.avatar || avatar} alt=""/>
                            <p className="phone">{user && user.userInfo.nickname}</p>
                        </div>
                        <ul className="control-list">
                            <li><Link to="/userCenter/actMan"><i className="act-control"/>我的订单</Link></li>
                            <li><Link to="/userCenter/famMan"><i className="member-control"/>家庭成员</Link></li>
                            <li><Link to="/userCenter"><i className="setting-control"/>设置</Link></li>
                        </ul>
                    </div>
                </div>
                
            </div>
        )
    }
}